package com.star.carservice.client.fragment.tabs;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

import com.star.carservice.R;
import com.star.carservice.client.AppController;
import com.star.carservice.client.activity.AddCarActivity;
import com.star.carservice.client.fragment.base.BaseFragment;
import com.star.carservice.client.fragment.parts.BannerFragment;
import com.star.carservice.client.utils.FormatUtils;
import com.star.carservice.client.utils.PreferencesUtils;
import com.star.carserviceapi.domain.CarInfo;
import com.star.carserviceapi.domain.request.QryLawsRequest;
import com.star.carserviceapi.domain.result.QryCarResult;
import com.star.carserviceapi.domain.result.QryLawsResult;

public class HomeFragment extends BaseFragment {

	private final static String TAG = HomeFragment.class.getSimpleName();

	@InjectView(R.id.btn_tab_car)
	Button btn_tab_car;

	@InjectView(R.id.btn_add_car)
	View btn_add_car;

	@InjectView(R.id.lbl_lows_price)
	TextView lbl_lows_price;

	@InjectView(R.id.lbl_lows_count)
	TextView lbl_lows_count;

	@InjectView(R.id.lbl_lows_score)
	TextView lbl_lows_score;

	View mCarsPopView = null;
	CarsPopWinHodler mCarsPopWinHodler = new CarsPopWinHodler();
	PopupWindow mCarsPopWindow = null;

	ArrayList<String> mDataCars = new ArrayList<String>();
	ArrayAdapter<String> mAdapterCars = null;

	List<CarInfo> mCarInfos = new ArrayList<CarInfo>();

	@Override
	public String getLogTag() {
		return TAG;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		execAsyncTask(new LoadCars());
	}

	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		super.onCreateView(inflater, container, savedInstanceState);

		if (CacheViewIsNull()) {
			mCacheView = inflater.inflate(R.layout.frag_home, container, false);
			getChildFragmentManager().beginTransaction()
					.replace(R.id.view_banner_panel, new BannerFragment())
					.commit();

			mCarsPopView = LayoutInflater.from(getActivity()).inflate(
					R.layout.pop_win_cars, null);

			ButterKnife.inject(this, mCacheView);

			ButterKnife.inject(mCarsPopWinHodler, mCarsPopView);

			initView();
		}

		removeCacheView();

		return mCacheView;
	}

	private void initView() {
		mAdapterCars = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_spinner_item, mDataCars);

		mCarsPopWinHodler.list_cars.setAdapter(mAdapterCars);
		mCarsPopWinHodler.list_cars.setSelected(true);

		mCarsPopWinHodler.list_cars
				.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int position, long arg3) {
						if (mCarsPopView.isShown()) {
							mCarsPopWindow.dismiss();
						}

						onCarChanged(position);
					}
				});
	}

	@SuppressWarnings("deprecation")
	@OnClick(R.id.btn_tab_car)
	public void showCars(View view) {
		if (mCarsPopWindow == null) {
			mCarsPopWindow = new PopupWindow(mCarsPopView,
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		}

		float popWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
				180, getResources().getDisplayMetrics());

		mCarsPopWindow.setWidth((int) popWidth);
		mCarsPopWindow.setBackgroundDrawable(new BitmapDrawable());
		mCarsPopWindow.setOutsideTouchable(true);

		mCarsPopWindow.showAsDropDown(view);
	}

	@OnClick(R.id.btn_add_car)
	public void addCars(View view) {
		startActivity(new Intent(getActivity(), AddCarActivity.class));
	}

	private int getCurrentCar(List<CarInfo> cars) {
		if (cars != null & cars.size() > 0) {
			return 0;
		}

		return 0;
	}

	private void onCarChanged(int postion) {
		CarInfo carInfo = mCarInfos.get(postion);

		btn_tab_car.setText(carInfo.getDesc());

		execAsyncTask(
				new LoadLows(),
				new QryLawsRequest(PreferencesUtils.getUserId(), carInfo
						.getId()));
	}

	class LoadLows extends AsyncTask<QryLawsRequest, Void, QryLawsResult> {

		@Override
		protected void onPreExecute() {
			lbl_lows_count.setText("");
			lbl_lows_price.setText("");
			lbl_lows_score.setText("");
		}

		@Override
		protected QryLawsResult doInBackground(QryLawsRequest... arg0) {

			return getApi()
					.qryLawsByUserId(arg0[0]);
		}

		@Override
		protected void onPostExecute(QryLawsResult result) {
			if (!result.successful()) {
				return;
			}

			lbl_lows_count.setText(result.getLawsCount() + "");
			lbl_lows_price.setText(FormatUtils.formatPrice(result
					.getLawsPrice()));
			lbl_lows_score.setText(result.getLawsScore() + "");
		}
	}

	class LoadCars extends AsyncTask<String, Void, QryCarResult> {

		@Override
		protected QryCarResult doInBackground(String... arg0) {

			return AppController.getInstance().getApi()
					.qryCarsByUserId(PreferencesUtils.getUserId());
		}

		@Override
		protected void onPostExecute(QryCarResult result) {

			if (!result.successful())
				return;

			if (!result.exsitCar()) {
				btn_tab_car.setVisibility(View.GONE);
				return;
			}

			btn_tab_car.setVisibility(View.VISIBLE);

			mDataCars.clear();
			for (CarInfo item : result.getCars()) {
				mDataCars.add(item.getDesc());
			}
			mAdapterCars.notifyDataSetChanged();

			int position = getCurrentCar(result.getCars());

			mCarInfos.clear();
			mCarInfos.addAll(result.getCars());

			onCarChanged(position);
		}
	}

	static class CarsPopWinHodler {
		@InjectView(R.id.list_cars)
		ListView list_cars;
	}
}
